<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row }" slot="menu">
        <div class="menu-option">
          <el-button icon="el-icon-view" size="small" type="text" v-if="permission.barcodeRecord_view" @click="rowView(row)">详情</el-button>
          <el-button v-if="permission.barcodeRecord_print" icon="el-icon-printer" size="small" type="text" @click="rowPrint(row)" :disabled="row.generationType === 'SCRAP'">
            <span v-if="row.isPrinted === 0">打印</span>
            <span v-if="row.isPrinted === 1">重打</span>
          </el-button>
          <!-- <el-button v-if="(row.type === 'MATERIAL' || row.type === 'SN') && permission.barcodeRecord_substitution" size="small" type="text" @click="rowSubstitution(row)"
            ><i class="iconicon_exchange" style="font-family: 'iconfont' !important; font-style: normal; padding-right: 5px"></i>置换</el-button
          > -->
          <el-button
            v-if="['MATERIAL', 'SN'].includes(row.type) && permission.barcodeRecord_scrap"
            icon="el-icon-delete"
            size="small"
            type="text"
            @click="rowScrap(row)"
            :disabled="row.generationType === 'SCRAP'"
            >作废</el-button
          >
        </div>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <el-dialog append-to-body :title="title" v-if="printInfoModel" :visible.sync="printInfoModel" width="35%">
      <div v-if="title === '重打'" style="display: flex; justify-content: center; margin-bottom: 10px">
        <span style="color: red">注：仅需修改流水号即可，重打的起始流水号和结束流水号需在原流水号范围内</span>
      </div>
      <avue-form ref="printForm" v-model="printInfo" :option="printInfoOption">
        <!-- <template slot="note">
          <span>注：仅需修改流水号即可，重打的起始流水号和结束流水号需在原流水号范围内</span>
        </template> -->
        <!-- <template slot="sequenceNumberTo">
          <span>{{ printInfo.sequenceNumberTo }}</span>
        </template> -->
        <!-- <template slot="sequenceNumberFromTo">
          <el-input style="width: 40%" v-model="printInfo.sequenceNumberFrom" placeholder="起始流水" readonly></el-input>
          &nbsp;&nbsp; - &nbsp;&nbsp;
          <el-input style="width: 40%" v-model="printInfo.sequenceNumberTo" placeholder="结束流水"></el-input>
        </template> -->
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="printSubmit"
          ><i class="el-icon-printer"></i><span>{{ title }}</span></el-button
        >
        <el-button size="small" @click="printInfoModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog append-to-body title="作废" :visible.sync="scrapModel" width="30%" @close="closeScrapModel">
      <avue-form ref="scrapForm" v-model="scrap" :option="scrapOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="scrapSubmit"><i class="el-icon-delete"></i><span>作 废</span></el-button>
        <el-button size="small" @click="scrapModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog append-to-body title="置换" :visible.sync="substitutionModel" width="30%">
      <avue-form ref="substitutionForm" v-model="substitution" :option="substitutionOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="substitutionSubmit">
          <i class="iconicon_exchange" style="font-family: 'iconfont' !important; font-style: normal; padding-right: 5px"></i><span>置 换</span>
        </el-button>
        <el-button size="small" @click="closeSubstitution"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog append-to-body @close="closeDetailModel" v-if="detailModal" class="detail" :visible.sync="detailModal" title="详情" width="60%" top="5vh">
      <avue-crud
        ref="crud"
        :table-loading="detailLoading"
        :data="detailData"
        :option="detailOption"
        :page.sync="detailPage"
        @current-change="currentDetailChange"
        @size-change="sizeDetailChange"
      >
        <template slot="menuLeft">
          <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
        </template>
      </avue-crud>
    </el-dialog>
    <export-comp ref="exportComp" page-api-url="mes-admin/sequence/generation/sn" :option="detailOption" :page="page" :query="exportParams" file-name="条码详情"> </export-comp>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import CommonPrintersTemplate from '@/components/common-printers-template/common-printers-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import exportComp from '@/components/export-comp';
import {
  getList,
  materialPrint,
  materialOtherPrint,
  snPrint,
  packPrint,
  sequenceScrap,
  materialSequenceReplace,
  snSequenceReplace,
  getPackingDetail,
  getProductDetail,
  matrialSequenceScrap,
  getPrinter
} from '@/api/admin/barcode-record';
import { mapGetters } from 'vuex';
import option from '@/option/user/info';
export default {
  name: 'AdminBarcodeRecord',
  components: {
    CommonModalTemplate,
    CommonPrintersTemplate,
    userTableConfig,
    exportComp
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'ADMIN_BARCODE_RECORD',
      form: {},
      query: {},
      loading: true,
      title: '',
      detailLoading: false,
      detailModal: false,
      flagType: false,
      scrapData: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      detailData: [],
      data: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        addBtn: false,
        delBtn: false,
        viewBtn: false,
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        indexLabel: '序号',
        menuWidth: 200,
        columnBtn: false,
        column: [
          {
            label: '单据编号',
            prop: 'orderNo',
            search: true,
            width: 200
          },
          {
            label: '条码类型',
            prop: 'type',
            search: true,
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=serial_number_rule_type'
          },
          {
            label: '条码规则名称',
            prop: 'sequenceDefinitionName',
            width: 150,
            search: true,
            searchLabelWidth: 100
          },
          {
            label: '条码规则编码',
            prop: 'sequenceDefinitionCode',
            width: 150,
            search: true,
            searchLabelWidth: 100
          },
          {
            label: '条码规则',
            prop: 'sequenceNumberFormat',
            width: 200
          },
          {
            label: '序列号',
            prop: 'sequenceNumber',
            hide: true,
            search: true
          },
          {
            label: '起始条码流水号',
            prop: 'sequenceNumberFrom',
            width: 200
          },
          {
            label: '结束条码流水号',
            prop: 'sequenceNumberTo',
            width: 200
          },
          {
            label: '条码总数',
            prop: 'quantity'
          },
          {
            label: '生成类型',
            prop: 'generationType',
            type: 'select',
            dicData: [
              { label: '正常', value: 'NORMAL' },
              { label: '作废', value: 'SCRAP' },
              { label: '增补', value: 'APPEND' },
              { label: '置换', value: 'REPLACE' },
              { label: '镭雕', value: 'LASER' }
            ]
            // search: true
          },
          {
            label: '状态',
            prop: 'isPrinted',
            html: true,
            formatter: (val) => {
              if (val.isPrinted == 0) {
                return '未打印';
              } else {
                return '已打印';
              }
            }
          },
          {
            label: '生成人',
            prop: 'operatorName'
          },
          {
            label: '生成时间',
            prop: 'createTime'
          },
          {
            label: '设备',
            prop: 'equipmentCode',
            search: true
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      detailOption: {
        addBtn: false,
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        delBtn: false,
        viewBtn: false,
        editBtn: false,
        selection: false,
        refreshBtn: false,
        menu: false,
        dialogClickModal: false,
        rowSelectionType: 'single',
        indexLabel: '序号',
        column: [
          {
            label: '产品序列号',
            prop: 'sequence'
          }
        ]
      },
      tableOption: {},
      printInfoModel: false,
      printInfo: {},
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '起始流水号',
            prop: 'startSequenceNumber',
            span: 20
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNumber',
            span: 20
          },
          // {
          //   label: '重打流水号范围',
          //   prop: 'sequenceNumberFromTo',
          //   row: true,
          //   span: 20,
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入重打流水号范围',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          }
        ]
      },
      scrapModel: false,
      scrap: {},
      scrapOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '原因说明',
            prop: 'remark',
            span: 24,
            type: 'textarea',
            maxlength: 50,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message: '请输入原因说明',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      substitutionModel: false,
      substitution: {},
      substitutionOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '起始流水号',
            prop: 'startSequenceNumber',
            span: 20,
            rules: [
              {
                required: true,
                message: '请输入起始流水号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNumber',
            span: 20,
            rules: [
              {
                required: true,
                message: '请输入结束流水号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '原因说明',
            prop: 'remarks',
            span: 20,
            rules: [
              {
                required: true,
                message: '请输入原因说明',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          }
        ]
      },
      timer: new Date().getTime(),
      modalName: '',
      sourceType: '',
      exportParams: {}
    };
  },
  computed: {
    ...mapGetters(['permission', 'userInfo'])
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    currentDetailChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      this.getDetail();
    },
    sizeDetailChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      this.getDetail();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      //   this.loading = false;
      //   this.data = [{ barCodeType: '', barCodeRule: '123' }];
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = this._map(data.records, (item) => {
          return {
            ...item,
            sheetNo: item.sheetNo || item.orderNo
          };
        });
        this.loading = false;
        //   this.selectionClear();
      });
    },
    async getDefaultPrinter() {
      const { user_id } = this.userInfo;
      try {
        const res = await getPrinter({ id: user_id });
        return res.data.data;
      } catch (e) {
        console.warn(e);
      }
    },
    closeDetailModel() {
      this.detailModal = false;
      this.detailData = [];
      this.detailPage = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
    },
    rowView(row) {
      this.form = row;
      console.log(row.type, 877766);
      let colType = this.findObject(this.detailOption.column, 'sequence');
      if (row.type === 'PRODUCTPACK') {
        colType.label = '成品包装条码';
      }
      if (row.type === 'MATERIAL') {
        colType.label = '原材料包装条码';
      }
      if (row.type === 'SN') {
        colType.label = '产品序列号';
      }
      this.detailModal = true;
      if (row.type === 'SN') {
        this.flagType = 'SN';
      } else {
        this.flagType = 'PRODUCT';
      }
      this.getDetail();
    },
    getDetail() {
      this.detailLoading = true;
      getPackingDetail(this.detailPage.currentPage, this.detailPage.pageSize, { id: this.form.id }).then((res) => {
        const data = res.data.data;
        this.detailData = data.records;
        this.detailPage.total = data.total;
        this.detailLoading = false;
      });
    },
    async rowPrint(row) {
      try {
        const printer = await this.getDefaultPrinter();
        const { labelTemplateId = '', printerId = '', equipmentName = '', templateFileName = '' } = printer;
        this.printInfo = {
          labelTemplateId: labelTemplateId,
          labelTemplateName: templateFileName,
          equipmentId: printerId,
          equipmentName
        };
      } catch (e) {
        console.warn(e);
      }
      this.printInfoModel = true;
      this.title = row.isPrinted === 0 ? '打印' : '重打';
      this.sourceType = row.type;
      this.$set(this.printInfo, 'generationId', row.id);
      let startColumn = this.findObject(this.printInfoOption.column, 'startSequenceNumber');
      let endColumn = this.findObject(this.printInfoOption.column, 'endSequenceNumber');
      if (row.isPrinted === 1) {
        this.printInfo.startSequenceNumber = row.sequenceNumberFrom;
        this.printInfo.endSequenceNumber = row.sequenceNumberTo;
        this.$set(startColumn, 'display', true);
        this.$set(endColumn, 'display', true);
      } else {
        this.$set(startColumn, 'display', false);
        this.$set(endColumn, 'display', false);
      }
    },
    closeScrapModel() {
      this.$refs.scrapForm.resetForm();
    },
    /**
     * 报废
     */
    rowScrap(row) {
      this.scrapData = row;
      this.scrapModel = true;
      this.scrap.sequenceGenerationId = row.id;
      this.scrap.startSequenceNumber = row.sequenceNumberFrom;
      this.scrap.endSequenceNumber = row.sequenceNumberTo;
    },
    /**
     * 置换
     */
    rowSubstitution(row) {
      this.substitutionModel = true;
      this.sourceType = row.type;
      this.$set(this.substitution, 'sequenceGenerationId', row.id);
      this.$set(this.substitution, 'startSequenceNumber', row.sequenceNumberFrom);
      this.$set(this.substitution, 'endSequenceNumber', row.sequenceNumberTo);
    },
    closeSubstitution() {
      this.substitutionModel = false;
      this.$refs.substitutionForm.resetFields();
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?status=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '标签名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '标签代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    },
    /**
     * 获取选中打印机标签模版信息
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'printersModal') {
        if (this.printInfoModel) {
          this.$set(this.printInfo, 'equipmentId', rowData.id);
          this.$set(this.printInfo, 'equipmentName', rowData.name);
        } else {
          this.$set(this.substitution, 'equipmentId', rowData.id);
          this.$set(this.substitution, 'equipmentName', rowData.name);
        }
      } else if (this.modalName === 'labelTemplateModal') {
        if (this.printInfoModel) {
          this.$set(this.printInfo, 'labelTemplateId', rowData.id);
          this.$set(this.printInfo, 'labelTemplateName', rowData.fileName);
        } else {
          this.$set(this.substitution, 'labelTemplateId', rowData.id);
          this.$set(this.substitution, 'labelTemplateName', rowData.fileName);
        }
      }
    },
    /**
     * 打印
     */
    printSubmit() {
      this.$refs.printForm.validate((valid, done) => {
        if (this.title === '重打') {
          this.printInfo.fromSequenceNumber = this._cloneDeep(this.printInfo.startSequenceNumber);
          this.printInfo.toSequenceNumber = this._cloneDeep(this.printInfo.endSequenceNumber);
          delete this.printInfo.startSequenceNumber;
          delete this.printInfo.endSequenceNumber;
        } else {
          delete this.printInfo.startSequenceNumber;
          delete this.printInfo.endSequenceNumber;
          delete this.printInfo.fromSequenceNumber;
          delete this.printInfo.toSequenceNumber;
        }
        delete this.printInfo.equipmentName;
        delete this.printInfo.labelTemplateName;
        if (valid) {
          switch (this.sourceType) {
            case 'MATERIAL':
              packPrint(this.printInfo).then(
                (res) => {
                  this.$refs.printForm.resetFields();
                  this.printInfoModel = false;
                  this.$message({
                    type: 'success',
                    message: res.data.msg
                  });
                  this.onLoad(this.page);
                  done();
                },
                (error) => {
                  done();
                }
              );
              break;
            case 'SN':
              snPrint(this.printInfo).then(
                (res) => {
                  this.$refs.printForm.resetFields();
                  this.printInfoModel = false;
                  this.$message({
                    type: 'success',
                    message: res.data.msg
                  });
                  this.onLoad(this.page);
                  done();
                },
                (error) => {
                  done();
                }
              );
              break;
            case 'PRODUCTPACK':
              packPrint(this.printInfo).then(
                (res) => {
                  this.$refs.printForm.resetFields();
                  this.printInfoModel = false;
                  this.$message({
                    type: 'success',
                    message: res.data.msg
                  });
                  this.onLoad(this.page);
                  done();
                },
                (error) => {
                  done();
                }
              );
              break;
          }
        }
      });
    },
    /**
     * 作废
     */
    scrapSubmit() {
      if (this.scrapData.type === 'MATERIAL' && this.scrapData.status !== 1) {
        this.$message.error('该条记录中关联的包装条码已使用，不允许作废！');
        return;
      }
      this.$refs.scrapForm.validate((valid, done) => {
        if (valid) {
          (this.scrapData.type === 'MATERIAL' ? matrialSequenceScrap(this.scrap) : sequenceScrap(this.scrap)).then(
            (res) => {
              this.$refs.scrapForm.resetFields();
              this.scrapModel = false;
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              this.onLoad(this.page);
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    /**
     * 置换
     */
    substitutionSubmit() {
      this.$refs.substitutionForm.validate((valid, done) => {
        if (valid) {
          this.substitution['sequenceGenerationId'] = this.substitution.sequenceGenerationId;
          switch (this.sourceType) {
            case 'MATERIAL':
              materialSequenceReplace(this.substitution).then(
                (res) => {
                  this.$refs.substitutionForm.resetFields();
                  this.substitutionModel = false;
                  this.$message({
                    type: 'success',
                    message: res.data.msg
                  });
                  this.onLoad(this.page);
                  done();
                },
                (error) => {
                  done();
                }
              );
              break;
            case 'SN':
              snSequenceReplace(this.substitution).then(
                (res) => {
                  this.$refs.substitutionForm.resetFields();
                  this.substitutionModel = false;
                  this.$message({
                    type: 'success',
                    message: res.data.msg
                  });
                  this.onLoad(this.page);
                  done();
                },
                (error) => {
                  done();
                }
              );
          }
        }
      });
    },
    handleExport() {
      this.exportParams['id'] = this.form.id;
      this.$refs.exportComp.visible = true;
    }
  }
};
</script>

<style scoped lang="scss">
.menu-option {
  text-align: left;
  padding: 0 30px;
}
.sequenceNumber {
  position: relative;
  padding: 8px 0 8px 0;
}
// .detail {
//   ::v-deep .el-table--small td {
//     padding: 0;
//   }
//   ::v-deep .el-table .cell {
//     padding: 0 0 0 8px;
//   }
// }
</style>
